package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ZhuHongKai
 * @version 1.0
 * @ClassName LoginCheckInterceptor
 * @date 2022/10/10 20:30
 */
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取登录用户
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) {
            // 后端用户以登录
            BaseContext.setCurrentId(empId);
            return true;
        }

        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            // 前端用户以登录
            BaseContext.setCurrentId(userId);
            return true;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        // 没有登录，则不放行
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
}
